package com.example.black.myapplication.mynet;

import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class Request implements IRequest {

    private static final String TAG = Request.class.getSimpleName();
    String url;
    /**
     * 网络请求数据
     */
    byte[] data;
    CallBackListener listener;

    public Request(String url, byte[] data, CallBackListener listener) {
        this.url = url;
        this.data = data;
        this.listener = listener;
    }

    public String getUrl() {
        return url;
    }

    @Override
    public void setUrl(String url) {
        this.url = url;
    }

    @Override
    public void setListener(CallBackListener listener) {
        this.listener = listener;
    }


    public CallBackListener getListener() {
        return listener;
    }



    @Override
    public void execute(){
            String message="";
        Log.e(TAG, "execute: " );
        URL url;
        HttpURLConnection connection = null;
        InputStream inputStream = null;
            try {
                url = new URL(getUrl());
                connection= (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("POST");
                connection.setDoOutput(true);
                connection.setDoInput(true);
                connection.setUseCaches(false);
                connection.setConnectTimeout(30000);
                connection.setReadTimeout(30000);
                connection.setRequestProperty("Content-type","application/x-javascript->json");
                connection.connect();
                OutputStream outputStream=connection.getOutputStream();
                outputStream.write(getData());
                outputStream.flush();
                outputStream.close();
                Log.e(TAG, "execute: getResponseCode"+connection.getResponseCode() );
                if (connection.getResponseCode() == 200){
                    inputStream = connection.getInputStream();
                    listener.onSuccess(inputStream);
                }else {
                    throw new RuntimeException("请求失败了");
                }



            } catch (Exception e) {
                Log.e(TAG, "execute: error",e );
                listener.onFailure(e);
                e.printStackTrace();
                throw new RuntimeException("请求失败了");
            }finally {
                if (inputStream != null){
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }
                if (connection != null){
                    connection.disconnect();
                }
            }

    }

    public byte[] getData() {
        return data;
    }

    @Override
    public void setData(byte[] data) {
        this.data = data;
    }
}
